package com.jajahome.util;

import android.app.Service;
import android.content.Intent;
import android.location.LocationManager;
import android.os.IBinder;
import androidx.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.jajahome.constant.Constant;
import com.jajahome.widget.SharedPreferencesUtils;

public class LocationSvc extends Service implements AMapLocationListener{
	private static final String TAG = "LocationSvc";
	private LocationManager locationManager;
	private AMapLocationClient locationClient = null;
	private AMapLocationClientOption locationOption = null;
	private String mcityName, mAdminArea, mUserCity;
	public static SharedPreferencesUtils sharedPreferencesUtils;

	@Nullable
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		sharedPreferencesUtils = new SharedPreferencesUtils(this);
		getLocation();
	}

	@Override
	public void onLocationChanged(AMapLocation aMapLocation) {
		mcityName = aMapLocation.getCity();//杭州市
		mAdminArea = aMapLocation.getProvince();//浙江省
		mUserCity = mAdminArea + " " + mcityName;
		sharedPreferencesUtils.saveUserCity(mcityName);
		//通知Activity
		Intent intent = new Intent();
		intent.setAction(Constant.LOCATION_ACTION);
		intent.putExtra(Constant.LOCATION, mUserCity);
		intent.putExtra(Constant.LOCATION_NAME ,mcityName);
		sendBroadcast(intent);
		// 如果只是需要定位一次，这里就移除监听，停掉服务。如果要进行实时定位，可以在退出应用或者其他时刻停掉定位服务。
		stopSelf();
		locationClient.onDestroy();
	}
	/*获取定位数据*/
	public void getLocation() {
		locationClient = new AMapLocationClient(this);
		locationClient.setLocationListener(this);
		locationOption = new AMapLocationClientOption();
		// 设置定位模式为低功耗模式
		locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
		locationOption.setNeedAddress(true);
		// 设置定位参数
		locationClient.setLocationOption(locationOption);
		// 启动定位
		locationClient.startLocation();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		locationClient.onDestroy();
	}

	@Override
	public boolean stopService(Intent name) {
		return super.stopService(name);
	}
}
